from rest_framework import viewsets, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from datetime import datetime, timedelta

from .models import  MarketSummary,StockPerformanceDaily, SectorPerformanceDaily, AmountEnergy
from .serializers import (
    MarketSummarySerializer,
    # StockPerformanceDailySerializer,
    # SectorPerformanceDailySerializer,
    # AmountEnergySerializer
)
from .tasks import analyze_market_data


class MarketSummaryViewSet(viewsets.ReadOnlyModelViewSet):
    """市场概览视图集"""
    queryset = MarketSummary.objects.all().order_by('-date')
    serializer_class = MarketSummarySerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['date', 'period']
    ordering_fields = ['date']
    
    @action(detail=False, methods=['get'])
    def latest(self, request):
        """获取最新的市场概览"""
        period = request.query_params.get('period', 'day')
        print(f'get latest!')
        
        latest = MarketSummary.objects.order_by('-date').first()
        if not latest:
            return Response({"error": "没有找到市场概览数据"}, status=404)
        
        serializer = self.get_serializer(latest)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'])
    def trend(self, request):
        """获取市场趋势数据"""
        period = request.query_params.get('period', 'day')
        days = int(request.query_params.get('days', 30))
        
        # 获取最近N天的市场概览数据
        end_date = datetime.now().date()
        start_date = end_date - timedelta(days=days)
        
        queryset = MarketSummary.objects.filter(
            date__gte=start_date,
            date__lte=end_date
        ).order_by('date')
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['post'])
    def run_analysis(self, request):
        """手动触发市场数据分析"""
        date = request.data.get('date')
        period = request.data.get('period', 'day')
        
        # 异步执行分析任务
        task = analyze_market_data.delay(date, period)
        
        return Response({
            "message": "市场数据分析任务已提交",
            "task_id": task.id
        })

# class StockPerformanceDailyViewSet(viewsets.ModelViewSet):
#     queryset = StockPerformanceDaily.objects.all()
#     serializer_class = StockPerformanceDailySerializer


# class SectorPerformanceDailyViewSet(viewsets.ModelViewSet):
#     queryset = SectorPerformanceDaily.objects.all()
#     serializer_class = SectorPerformanceDailySerializer


# class AmountEnergyViewSet(viewsets.ModelViewSet):
#     queryset = AmountEnergy.objects.all()
#     serializer_class = AmountEnergySerializer